package com.asiainfo.dacp.datastash.broker.listener;

import com.asiainfo.dacp.core.BeanFactory;
import com.asiainfo.dacp.datastash.broker.core.enums.UnitTaskStateEnum;
import com.asiainfo.dacp.datastash.broker.core.vo.StashUnitTask;
import com.asiainfo.dacp.datastash.broker.facade.UnitTaskFacade;
import com.asiainfo.dacp.datastash.broker.facade.UnitWorkFacade;
import com.asiainfo.dacp.datastash.broker.facade.state.UnitTaskStateLogService;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogVo;
import com.asiainfo.dacp.datastash.broker.tracelog.StashTraceLogger;
import com.asiainfo.dacp.datastash.broker.util.CallableResult;
import com.asiainfo.dacp.datastash.broker.workerctrl.StashWorkExecutorByEngine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;

/**
 * 监听Broker的工作队列（broker_{brokerId}_work_queue）
 *
 *
 * @author MeiKefu
 * @date 2017-11-21
 */
public class UnitWorkQueueListener extends AbstractQueueListener {
    private static Logger LOG = LoggerFactory.getLogger(UnitWorkQueueListener.class);

    private String clzName = this.getClass().getSimpleName();

    @Async
    protected void handle(){
        StashTraceLogger tracelog = BeanFactory.getBean(StashTraceLogger.class);

        UnitWorkFacade unitWorkFacade = BeanFactory.getBean(UnitWorkFacade.class);
        UnitTaskStateLogService taskLog = BeanFactory.getBean(UnitTaskStateLogService.class);
 
        StashUnitTask stashUnitTask = unitWorkFacade.fetchWork();

        if(stashUnitTask!=null){
        	 
        	stashUnitTask.running();
        	taskLog.update(stashUnitTask, UnitTaskStateEnum.RUNNING);
        	
        	
        	//fix 按引擎执行任务，引擎部署需要符合规范，因此最好有个部署的pom文件或工程
            //StashWorkExecutor stashWorkExecutor = BeanFactory.getBean(StashWorkExecutor.class);
            StashWorkExecutorByEngine stashWorkExecutor = BeanFactory.getBean(StashWorkExecutorByEngine.class);

            tracelog.info(StashTraceLogVo.buildStashTraceLogVo(stashUnitTask,clzName,"fetch","获取task开始执行"));


			stashWorkExecutor.execute(stashUnitTask);

        }
    }

}
